package cn.cloudbae.schedule;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;

import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;

import cn.cloudbae.kit.PortKit;
import cn.cloudbae.kit.Randomkit;
import cn.cloudbae.service.JobLifeCycleService;

public class RestartJob implements SimpleJob{

	@Autowired
	JobLifeCycleService jobLifeCycleService;
	
	@Override
	public void execute(ShardingContext context) {
		String jobName = context.getJobName();
		
		int i = Randomkit.nextInt(0, 100);
		boolean flag = false;
		if(flag) { //模拟job执行成功
			String port = String.valueOf(PortKit.getPort()); //获得运行时端口
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
			String now = sdf.format(new Date());
	        System.out.println(now + "FirstJob at　" +port + ", " + context.toString());
		} else { //模拟job执行失败
			long time = System.currentTimeMillis() + 1000 * 60 * 60; //1小时后重跑job
            SimpleDateFormat sdf = new SimpleDateFormat("HH");
            if(!sdf.format(new Date(time)).equals("23")){//如果一直失败到晚上23点，则发送预警信息（暂时未做）
                //sendWarnMsgService.sendWarnMsg(errorMechants);
                String cron = JobLifeCycleService.getCron(new Date(time));
                String customJobName = "fail_job_" + time + "_" + context.getShardingItem();
                String desc = "任务：" + jobName+ "发生错误，现另起任务重跑失败项";
                //customjob只分一片，但三台机都会执行customJob，各自重跑失败的记录
                //通过jobName中的item划分，也可以通过0=X划分。思路：如果这次job在机器A执行失败，则下次依然在机器A上重跑
                jobLifeCycleService.scheludeJob(customJobName,this.getClass(), new Object [] {}, 1,"0="+context.getShardingItem(), cron, desc);
            }
		}
	}
	
}
